(function() {
    // 防止重复注入
    if (window.elementInspectorLoaded) {
        console.log('元素检查器已加载');
        return;
    }
    window.elementInspectorLoaded = true;

    let isSelecting = false;
    let overlay = null;
    let listeners = [];
    let highlightTimeout = null;

    /**
     * 创建高亮覆盖层
     */
    function createOverlay() {
        if (overlay) return;

        overlay = document.createElement('div');
        overlay.id = 'playwright-element-overlay';
        overlay.style.cssText = `
            position: absolute;
            border: 2px solid #ff6b35;
            background-color: rgba(255, 107, 53, 0.1);
            pointer-events: none;
            z-index: 999999;
            display: none;
            box-shadow: 0 0 10px rgba(255, 107, 53, 0.5);
            border-radius: 2px;
            transition: all 0.1s ease;
        `;
        document.body.appendChild(overlay);

        // 创建信息提示框
        const tooltip = document.createElement('div');
        tooltip.id = 'playwright-element-tooltip';
        tooltip.style.cssText = `
            position: absolute;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-family: monospace;
            z-index: 1000000;
            display: none;
            max-width: 300px;
            word-wrap: break-word;
        `;
        document.body.appendChild(tooltip);
        overlay.tooltip = tooltip;
    }

    /**
     * 移除覆盖层
     */
    function removeOverlay() {
        if (overlay && overlay.parentNode) {
            overlay.parentNode.removeChild(overlay);
            if (overlay.tooltip && overlay.tooltip.parentNode) {
                overlay.tooltip.parentNode.removeChild(overlay.tooltip);
            }
            overlay = null;
        }
    }

    /**
     * 高亮元素
     */
    function highlightElement(element) {
        if (!overlay || !element) return;

        const rect = element.getBoundingClientRect();
        const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
        const scrollY = window.pageYOffset || document.documentElement.scrollTop;

        overlay.style.left = (rect.left + scrollX) + 'px';
        overlay.style.top = (rect.top + scrollY) + 'px';
        overlay.style.width = rect.width + 'px';
        overlay.style.height = rect.height + 'px';
        overlay.style.display = 'block';

        // 显示元素信息
        showElementTooltip(element, rect, scrollX, scrollY);
    }

    /**
     * 显示元素信息提示
     */
    function showElementTooltip(element, rect, scrollX, scrollY) {
        if (!overlay.tooltip) return;

        const tagName = element.tagName.toLowerCase();
        const id = element.id ? `#${element.id}` : '';
        const className = element.className ? `.${element.className.split(' ').join('.')}` : '';
        const text = element.textContent ? element.textContent.trim().substring(0, 30) : '';

        const tooltipText = `${tagName}${id}${className}${text ? ` "${text}"` : ''}`;

        overlay.tooltip.textContent = tooltipText;
        overlay.tooltip.style.left = (rect.left + scrollX) + 'px';
        overlay.tooltip.style.top = (rect.top + scrollY - 30) + 'px';
        overlay.tooltip.style.display = 'block';
    }

    /**
     * 隐藏覆盖层
     */
    function hideOverlay() {
        if (overlay) {
            overlay.style.display = 'none';
            if (overlay.tooltip) {
                overlay.tooltip.style.display = 'none';
            }
        }
    }

    /**
     * 收集元素信息
     */
    function collectElementInfo(element) {
        const computedStyle = window.getComputedStyle(element);

        return {
            tagName: element.tagName.toLowerCase(),
            id: element.id || '',
            className: element.className || '',
            textContent: (element.textContent || '').trim().substring(0, 100),
            name: element.name || '',
            placeholder: element.placeholder || '',
            value: element.value || '',
            type: element.type || '',
            href: element.href || '',
            src: element.src || '',
            alt: element.alt || '',
            title: element.title || '',
            role: element.getAttribute('role') || '',
            ariaLabel: element.getAttribute('aria-label') || '',
            dataTestId: element.getAttribute('data-testid') || element.getAttribute('data-test-id') || '',
            xpath: getElementXPath(element),
            cssSelector: generateCssSelector(element),
            position: {
                x: element.getBoundingClientRect().left,
                y: element.getBoundingClientRect().top,
                width: element.getBoundingClientRect().width,
                height: element.getBoundingClientRect().height
            },
            visibility: computedStyle.visibility,
            display: computedStyle.display
        };
    }

    /**
     * 生成元素XPath
     */
    function getElementXPath(element) {
        if (element.id !== '') {
            return `//*[@id="${element.id}"]`;
        }
        if (element === document.body) {
            return '/html/body';
        }

        let ix = 0;
        const siblings = element.parentNode.childNodes;
        for (let i = 0; i < siblings.length; i++) {
            const sibling = siblings[i];
            if (sibling === element) {
                return getElementXPath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
            }
            if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
                ix++;
            }
        }
    }

    /**
     * 生成CSS选择器
     */
    function generateCssSelector(element) {
        if (element.id) {
            return '#' + element.id;
        }

        let selector = element.tagName.toLowerCase();

        if (element.className) {
            const classes = element.className.split(' ').filter(c => c.trim());
            if (classes.length > 0) {
                selector += '.' + classes.join('.');
            }
        }

        // 如果选择器不唯一，添加父级信息
        if (document.querySelectorAll(selector).length > 1) {
            let parent = element.parentElement;
            if (parent && parent !== document.body) {
                return generateCssSelector(parent) + ' > ' + selector;
            }
        }

        return selector;
    }

    /**
     * 添加事件监听器
     */
    function addEventListeners() {
        const mouseoverHandler = function(e) {
            if (!isSelecting) return;
            e.preventDefault();

            // 防抖处理
            if (highlightTimeout) {
                clearTimeout(highlightTimeout);
            }
            highlightTimeout = setTimeout(() => {
                highlightElement(e.target);
            }, 50);
        };

        const mouseoutHandler = function(e) {
            if (!isSelecting) return;
            if (highlightTimeout) {
                clearTimeout(highlightTimeout);
            }
            hideOverlay();
        };

        const clickHandler = function(e) {
            if (!isSelecting) return;
            e.preventDefault();
            e.stopPropagation();

            const element = e.target;
            const elementInfo = collectElementInfo(element);

            console.log('ELEMENT_SELECTED:' + JSON.stringify(elementInfo));

            // 如果定位器生成器可用，直接调用
            if (typeof window.generateLocators === 'function') {
                try {
                    window.generateLocators(JSON.stringify(elementInfo));
                } catch (error) {
                    console.error('定位器生成失败:', error);
                    console.log('ELEMENT_SELECTED:' + JSON.stringify(elementInfo));
                }
            }

            // 临时停止选择以避免连续触发
            isSelecting = false;
            hideOverlay();

            setTimeout(() => {
                if (confirm('继续选择其他元素？\n点击"确定"继续，"取消"停止选择')) {
                    isSelecting = true;
                    console.log('🔄 继续选择模式...');
                } else {
                    stopElementSelection();
                }
            }, 100);
        };

        const keydownHandler = function(e) {
            if (!isSelecting) return;

            // ESC键停止选择
            if (e.key === 'Escape') {
                e.preventDefault();
                stopElementSelection();
                console.log('⚡ 通过ESC键停止选择');
            }
        };

        document.addEventListener('mouseover', mouseoverHandler, true);
        document.addEventListener('mouseout', mouseoutHandler, true);
        document.addEventListener('click', clickHandler, true);
        document.addEventListener('keydown', keydownHandler, true);

        listeners = [
            { type: 'mouseover', handler: mouseoverHandler },
            { type: 'mouseout', handler: mouseoutHandler },
            { type: 'click', handler: clickHandler },
            { type: 'keydown', handler: keydownHandler }
        ];
    }

    /**
     * 移除事件监听器
     */
    function removeEventListeners() {
        listeners.forEach(listener => {
            document.removeEventListener(listener.type, listener.handler, true);
        });
        listeners = [];

        if (highlightTimeout) {
            clearTimeout(highlightTimeout);
            highlightTimeout = null;
        }
    }

    // 全局函数：开始元素选择
    window.startElementSelection = function() {
        if (isSelecting) {
            console.log('✅ 元素选择模式已经启动');
            return;
        }

        createOverlay();
        isSelecting = true;
        addEventListeners();

        console.log('🎯 元素选择模式已启动！');
        console.log('💡 鼠标悬停可预览元素，点击选择元素');
        console.log('⚡ 按ESC键或输入 stopElementSelection() 停止选择');

        // 显示页面提示
        showPageNotification('🎯 元素选择模式已启动\n💡 悬停预览，点击选择\n⚡ 按ESC退出');
    };

    // 全局函数：停止元素选择
    window.stopElementSelection = function() {
        isSelecting = false;
        removeEventListeners();
        hideOverlay();
        removeOverlay();
        hidePageNotification();
        console.log('🛑 元素选择模式已停止');
    };

    // 全局函数：重新注入（用于调试）
    window.reinjectInspector = function() {
        window.elementInspectorLoaded = false;
        stopElementSelection();
        setTimeout(() => {
            location.reload();
        }, 100);
    };

    // 全局函数：显示帮助信息
    window.showInspectorHelp = function() {
        console.log('🔧 Playwright 元素检查器帮助');
        console.log('='.repeat(40));
        console.log('📝 可用命令：');
        console.log('  startElementSelection() - 开始选择元素');
        console.log('  stopElementSelection()  - 停止选择元素');
        console.log('  showInspectorHelp()     - 显示此帮助');
        console.log('  reinjectInspector()     - 重新注入检查器');
        console.log('');
        console.log('⌨️  快捷键：');
        console.log('  ESC键 - 停止元素选择');
        console.log('='.repeat(40));
    };

    /**
     * 显示页面通知
     */
    function showPageNotification(message) {
        const notification = document.createElement('div');
        notification.id = 'playwright-notification';
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(255, 107, 53, 0.9);
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            font-family: Arial, sans-serif;
            font-size: 14px;
            z-index: 1000001;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            white-space: pre-line;
            max-width: 300px;
        `;
        notification.textContent = message;
        document.body.appendChild(notification);

        // 3秒后自动隐藏
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }

    /**
     * 隐藏页面通知
     */
    function hidePageNotification() {
        const notification = document.getElementById('playwright-notification');
        if (notification && notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }

    console.log('🔧 Playwright 元素检查器已准备就绪！');
    console.log('🚀 输入 startElementSelection() 开始选择元素');
    console.log('❓ 输入 showInspectorHelp() 查看完整帮助');
})();
